package com.wing.oauth2.filter;

import com.wing.oauth2.exception.ValidateCodeException;
import com.wing.redis.utils.redis.RedisHelperImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Profile;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码过滤器
 *
 * @author
 */
//@Profile({"test","pro"})
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {

    @Lazy
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private RedisHelperImpl redisHelper;

    @Value("${spring.profiles.active}")
    private String env;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
//        logger.info(httpServletRequest.getRequestURI());
//        logger.info(httpServletRequest.getMethod());
//        logger.info(httpServletRequest.getRemoteHost());
        String captcha = httpServletRequest.getParameter("captcha");

        if ("/oauth2/admin/user/login".equalsIgnoreCase(httpServletRequest.getRequestURI()) && httpServletRequest.getMethod().equals("POST")&&
                StringUtils.isNotBlank(captcha)&&"pro".equals(env)) {
            try {
                String captchaKey = httpServletRequest.getParameter("captchaKey");
                String grantType = httpServletRequest.getParameter("grant_type");
                if(!StringUtils.isEmpty(grantType) && grantType.equals("password")){
                    validateCode(captchaKey,captcha);
                }
            } catch (ValidateCodeException e) {
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
                return;
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private void validateCode(String captchaKey, String captcha) {

        if (StringUtils.isBlank(captchaKey)) {
            throw new ValidateCodeException("验证码key不能为空！");
        }
        if (StringUtils.isBlank(captcha)) {
            throw new ValidateCodeException("验证码不能为空！");
        }

        String key = "captcha:" + captchaKey;
        String captchaValue = (String)redisHelper.getValue(key);

        if (StringUtils.isBlank(captchaValue)) {
            throw new ValidateCodeException("验证码不存在！");
        }
        if (!captchaValue.equalsIgnoreCase(captcha)) {
            throw new ValidateCodeException("验证码不正确！");
        }
        redisHelper.remove(key);
    }

}